package com.wuxin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuxin.entity.UserAccount;
import com.wuxin.entity.UserInfo;
import com.wuxin.entity.UserLoginRecord;
import com.wuxin.entity.vo.*;
import com.wuxin.mapper.UserAccountMapper;
import com.wuxin.mapper.UserInfoMapper;
import com.wuxin.mapper.UserLoginRecordMapper;
import com.wuxin.result.Result;
import com.wuxin.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuxin.util.JwtUtils;
import com.wuxin.util.MD5;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author wuxin
 * @since 2025-01-13
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserAccountMapper userAccountMapper;
    @Autowired
    private UserLoginRecordMapper userLoginRecordMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result  register(RegisterVO registerVO) {
        //判断用户是否已经注册过了
        QueryWrapper<UserInfo> userInfoQueryWrapper =  new QueryWrapper<>();
        userInfoQueryWrapper.eq("mobile",registerVO.getMobile());
        Integer count = baseMapper.selectCount(userInfoQueryWrapper);
        //判断count
        if (count != null && count > 0) {
//            throw new RuntimeException("该手机号已被注册");
//            System.out.println("该手机号已被注册");
            return Result.error().message("该手机号已被注册");
        }
        //用户信息增加
        UserInfo u = new UserInfo();
        u.setUserType(registerVO.getUserType());
        u.setNickName(registerVO.getMobile());
        u.setMobile(registerVO.getMobile());
        u.setName(registerVO.getMobile());
        u.setPassword(MD5.encrypt(registerVO.getPassword()));//密码MD5加密
        u.setStatus(UserInfo.STATUS_NORMAL);//状态
        u.setHeadImg("https://2409jinrong.oss-cn-beijing.aliyuncs.com/jinrong/2025/01/17/38b413bf-f5da-4dbf-aa94-2950e982f733.png");
        baseMapper.insert(u);

        //创建会员账户信息
        UserAccount ua = new UserAccount();
        ua.setUserId(u.getId());
        userAccountMapper.insert(ua);
        return Result.ok().message("注册成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserInfoVO login(LoginVO loginVO, String ip) {
        String mobile = loginVO.getMobile();
        String password = loginVO.getPassword();
        Integer userType = loginVO.getUserType();
        //StringUtils.isEmpty()判断
/*        if ( StringUtils.isEmpty(password)) {
                throw new BusinessException(ResponseEnum.PASSWORD_EMPTY_ERROR);
        }
        if ( StringUtils.isEmpty(mobile)) {
                throw new BusinessException(ResponseEnum.MOBILE_EMPTY_ERROR);
        }*/
        //非空 待填写


        //获取会员信息
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        wrapper.eq("user_type",userType);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        //判断是否为空

        //密码需要判断加密后进行对比

        //记录登录日志
        UserLoginRecord ulr = new UserLoginRecord();
        ulr.setUserId(userInfo.getId());
        ulr.setIp(ip);
        //添加到数据库中
        userLoginRecordMapper.insert(ulr);
        //生成token
        String token  = JwtUtils.createToken(userInfo.getId(),userInfo.getName());

        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setToken(token);
        userInfoVO.setName(userInfo.getName());
        userInfoVO.setNickName(userInfo.getNickName());
        userInfoVO.setHeadImg(userInfo.getHeadImg());
        userInfoVO.setMobile(userInfo.getMobile());
        userInfoVO.setUserType(userInfo.getUserType());

        return userInfoVO;
    }


    @Override
    public UserIndexVO getUserIndexVoByUserId(Long userId) {

        /*
            @ApiModelProperty(value = "上次登录时间")
            private Date lastLoginTime;

            @ApiModelProperty(value = "头像")
            private String headImg;


            @ApiModelProperty(value = "yonghuming")
            private String name;
         */
        UserIndexVO userIndexVO = new UserIndexVO();
        //多次登录，不能用selectOne()
        //分页 倒序 拿第一条
        QueryWrapper<UserLoginRecord> wrapper = new QueryWrapper<>();

        wrapper.eq("user_id",userId).orderByDesc("id").last("limit 1");
        UserLoginRecord userLoginRecord = userLoginRecordMapper.selectOne(wrapper);


        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("id",userId);

        UserInfo userInfo = baseMapper.selectOne(userInfoQueryWrapper);

        //最后登录时间
        userIndexVO.setLastLoginTime(userLoginRecord.getUpdateTime());
        userIndexVO.setName(userInfo.getName());
        userIndexVO.setHeadImg(userInfo.getHeadImg());

        return userIndexVO;
    }

    @Override
    public IPage<UserInfo> listPage(Page<UserInfo> pages, UserInfoQuery userInfoQuery) {


        //判断对象是否为空 不为空 获取对象
        String mobile = userInfoQuery.getMobile();
        Integer userType = userInfoQuery.getUserType();
        Integer status = userInfoQuery.getStatus();

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();

        if (userInfoQuery == null) {
            //用户未填写筛选条件
            return baseMapper.selectPage(pages,null);
        }

        wrapper.eq(StringUtils.isNotBlank(mobile),"mobile",mobile)
                .eq(status!=null,"status",status)
                .eq(status!=null,"user_type",userType);

        return baseMapper.selectPage(pages,wrapper);
    }

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setStatus(status);

        baseMapper.updateById(userInfo);

    }
}
